package com.example.rpcdemo.core.client;

import com.example.rpcdemo.core.protocol.RpcRequest;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class RpcProxy implements InvocationHandler {
    private final RpcClient client;
    
    public RpcProxy(RpcClient client) {
        this.client = client;
    }
    
    @SuppressWarnings("unchecked")
    public static <T> T createProxy(Class<T> interfaceClass, RpcClient client) {
        return (T) Proxy.newProxyInstance(
                interfaceClass.getClassLoader(),
                new Class<?>[]{interfaceClass},
                new RpcProxy(client)
        );
    }
    
    @SuppressWarnings("unchecked")
    public <T> T create(Class<T> interfaceClass, String serviceName) {
        return (T) Proxy.newProxyInstance(
                interfaceClass.getClassLoader(),
                new Class<?>[]{interfaceClass},
                this
        );
    }
    
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        RpcRequest request = new RpcRequest(
                method.getDeclaringClass().getName(),
                method.getName(),
                args,
                method.getParameterTypes()
        );
        
        return client.sendRequest(request);
    }
}